package com.sbhotel.chotellauncher.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.sbhotel.chotellauncher.R;
import com.sbhotel.chotellauncher.adapter.WifiScanAdapter;
import com.sbhotel.chotellauncher.constant.Constants;
import com.sbhotel.chotellauncher.util.SPUtil;
import com.sbhotel.chotellauncher.util.Utils;
import com.sbhotel.chotellauncher.util.WifiUtil;
import com.sbhotel.chotellauncher.widget.WifiPwdDialog;

import java.util.ArrayList;
import java.util.List;

public class WifiConnectActivity extends Activity {

    ListView wifiList;
    private WifiManager wifiManager;
    List<ScanResult> list;
    private MyWifiReceiver receiver;
    private WifiScanAdapter adapter;
    private WifiUtil wiFiAdmin;
    TextView activityTitle;
    WifiPwdDialog dialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_wifi);
        initView();
        initData();

    }

    @Override
    protected void onResume() {
        super.onResume();
        boolean netError = (boolean) SPUtil.get(this, Constants.SP_KEY_NET_ERROR, false);
        Log.d("leihuiming", "WifiConnectActivity onResume netError = " + netError);
        if(!netError) {
            finish();
        }
    }

    public void initView() {
        wifiList = findViewById(R.id.lv_wifi);
        wifiList.setItemsCanFocus(true);
        activityTitle = findViewById(R.id.activity_title);
        activityTitle.setText("无线网络");
    }

    public void initData() {
        //initTitleBar("无线网络", "");
        wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        /*scanResultList = wifiManager.getScanResults();*/
        adapter = new WifiScanAdapter(this);
        adapter.setClickListner(wiFiItemClickListner);
        wifiList.setAdapter(adapter);
        //listViewClick();

        wiFiAdmin = new WifiUtil(this);
        wiFiAdmin.openWifi();
        if (wifiManager.setWifiEnabled(true)) {
            //refreshWifiList();
            mHandler.post(wifiRunnable);
        }
        receiver = new MyWifiReceiver();

        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
        registerReceiver(receiver, filter);
    }

    Runnable wifiRunnable = new Runnable() {
        @Override
        public void run() {
            mHandler.postDelayed(wifiRunnable, 10000);
            wiFiAdmin.startScan(getApplicationContext());
            list = wiFiAdmin.getmWifiList();
            mHandler.sendEmptyMessage(1);
        }
    };

    Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 1) { //扫描完毕 设置数据
                adapter.setList(list);
            }/* else if (msg.what == HM_WIFI_CHANGED) {
                Log.d("leihuiming", "handle message HM_WIFI_CHANGED");
                HM_WIFI_ID = msg.arg1;
                wiFiAdmin.ConnectWifi(HM_WIFI_ID);
                adpter.setList(list);
            }*/
            return false;
        }
    });

    WifiScanAdapter.WiFiItemClickListner wiFiItemClickListner = new WifiScanAdapter.WiFiItemClickListner() {
        @Override
        public void onItemClick(int position) {
            String wifiItemSSID = list.get(position).SSID;
            //final TextView connectText = (TextView) view.findViewById(R.id.connect_state_text);
            Log.d("leihuiming", "position=" + position + " wifiItemSSID = " + wifiItemSSID
                    + " capabilities=" + list.get(position).capabilities);
            if (list.get(position).capabilities.equals("[ESS]")) {
                Log.d(Constants.LOG_TAG, "wifi_no_pwd");
                WifiConfiguration config = new WifiConfiguration();
                config.allowedAuthAlgorithms.clear();
                config.allowedGroupCiphers.clear();
                config.allowedKeyManagement.clear();
                config.allowedPairwiseCiphers.clear();
                config.allowedProtocols.clear();
                config.SSID = "\"" + wifiItemSSID + "\"";
                config.wepKeys[0] = "\"" + "\"";
                config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                config.wepTxKeyIndex = 0;
                if (config != null) {
                    wifiManager.addNetwork(config);
                }
            } else {
                // 没有配置好信息，配置
                Log.d("leihuiming", "pswDialog show");
                dialog = new WifiPwdDialog(WifiConnectActivity.this, list.get(position));
                dialog.show();
                    /*final WifiConnectDialog pswDialog = new WifiConnectDialog(
                            ConnectWifiActivity.this, R.style.MyDialogTheme,
                            new WifiConnectDialog.OnCustomDialogListener() {
                                @Override
                                public void back(String str) {
                                    if (null == str || str.length() < 8) {
                                        Toast.makeText(ConnectWifiActivity.this, getResources().getString(R.string.set_ap_pwd_hint), Toast.LENGTH_SHORT).show();
                                        return;
                                    }
                                    connectText.setText(getResources().getString(R.string.wifi_werify));
                                    wifiPassword = str;
                                    if (wifiPassword != null) {
                                        int netId = -1;
                                        if (list.get(position).capabilities.contains("WEP")) {
                                            netId = wiFiAdmin.AddWifiConfig(list, wifiItemSSID, wifiPassword, 2);
                                        } else if (list.get(position).capabilities.contains("WPA")) {
                                            netId = wiFiAdmin.AddWifiConfig(list, wifiItemSSID, wifiPassword, 3);
                                        }
                                        if (netId != -1) {
                                            Message msg = mHandler.obtainMessage(HM_WIFI_CHANGED);
                                            msg.arg1 = netId;
                                            mHandler.sendMessage(msg);
                                        } else {
                                            // 网络连接错误
                                            Toast.makeText(ConnectWifiActivity.this, getResources().getString(R.string.wifi_error_connect), Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                }
                            });
                    pswDialog.setTitle(wifiItemSSID);
                    pswDialog.show();*/
                //}
            }

        }
    };

    //listView点击事件
    private void listViewClick() {
        Log.d("leihuiming", "listViewClick");
        wifiList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            String wifiItemSSID = null;

            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                wifiItemSSID = list.get(position).SSID;
                //final TextView connectText = (TextView) view.findViewById(R.id.connect_state_text);
                Log.d("leihuiming", "position=" + position + " wifiItemSSID = " + wifiItemSSID
                 + " capabilities=" + list.get(position).capabilities);
                if (list.get(position).capabilities.equals("[ESS]")) {
                    Log.d(Constants.LOG_TAG, "wifi_no_pwd");
                    WifiConfiguration config = new WifiConfiguration();
                    config.allowedAuthAlgorithms.clear();
                    config.allowedGroupCiphers.clear();
                    config.allowedKeyManagement.clear();
                    config.allowedPairwiseCiphers.clear();
                    config.allowedProtocols.clear();
                    config.SSID = "\"" + wifiItemSSID + "\"";
                    config.wepKeys[0] = "\"" + "\"";
                    config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                    config.wepTxKeyIndex = 0;
                    if (config != null) {
                        wifiManager.addNetwork(config);
                    }
                } else {
                    // 没有配置好信息，配置
                    Log.d("leihuiming", "pswDialog show");
                    new WifiPwdDialog(WifiConnectActivity.this, list.get(position)).show();
                    /*final WifiConnectDialog pswDialog = new WifiConnectDialog(
                            ConnectWifiActivity.this, R.style.MyDialogTheme,
                            new WifiConnectDialog.OnCustomDialogListener() {
                                @Override
                                public void back(String str) {
                                    if (null == str || str.length() < 8) {
                                        Toast.makeText(ConnectWifiActivity.this, getResources().getString(R.string.set_ap_pwd_hint), Toast.LENGTH_SHORT).show();
                                        return;
                                    }
                                    connectText.setText(getResources().getString(R.string.wifi_werify));
                                    wifiPassword = str;
                                    if (wifiPassword != null) {
                                        int netId = -1;
                                        if (list.get(position).capabilities.contains("WEP")) {
                                            netId = wiFiAdmin.AddWifiConfig(list, wifiItemSSID, wifiPassword, 2);
                                        } else if (list.get(position).capabilities.contains("WPA")) {
                                            netId = wiFiAdmin.AddWifiConfig(list, wifiItemSSID, wifiPassword, 3);
                                        }
                                        if (netId != -1) {
                                            Message msg = mHandler.obtainMessage(HM_WIFI_CHANGED);
                                            msg.arg1 = netId;
                                            mHandler.sendMessage(msg);
                                        } else {
                                            // 网络连接错误
                                            Toast.makeText(ConnectWifiActivity.this, getResources().getString(R.string.wifi_error_connect), Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                }
                            });
                    pswDialog.setTitle(wifiItemSSID);
                    pswDialog.show();*/
                    //}
                }
            }
        });
    }

    private class MyWifiReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            int networkId = -1;
            if (intent.getAction() == WifiManager.NETWORK_STATE_CHANGED_ACTION) {
                Log.d(Constants.LOG_TAG, "ACTION=NETWORK_STATE_CHANGED_ACTION");
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                Log.d(Constants.LOG_TAG, "wifi_ssid=" + wifiInfo.getSSID());
                networkId = wifiInfo.getNetworkId();
                if (Utils.isWifiConnected(context)) {
                    //refreshWifiList();
                    //Toast.makeText(WifiConnectActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
                    Log.d("leihuiming", "wifi connected finish");
                    WifiConnectActivity.this.finish();
                }
            }
            adapter.notifyDataSetChanged();
            if (intent.getAction() == WifiManager.SUPPLICANT_STATE_CHANGED_ACTION) {
                Log.d(Constants.LOG_TAG, "ACTION=SUPPLICANT_STATE_CHANGED_ACTION");
                int linkWifiResult = intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR, 123);
                if (linkWifiResult == WifiManager.ERROR_AUTHENTICATING) {
                    Log.d(Constants.LOG_TAG, "ACTION=ERROR_AUTHENTICATING");
                    //wiFiAdmin.disConnectionWifi(HM_WIFI_ID);
                    //wifiManager.removeNetwork(HM_WIFI_ID);
                    //wifiManager.saveConfiguration();
                    if (networkId != -1) {
                        wifiManager.disableNetwork(networkId);
                        wifiManager.removeNetwork(networkId);
                    }
                    //Toast.makeText(WifiConnectActivity.this, "连接失败", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    @Override
    public void onBackPressed() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(receiver != null) {
            unregisterReceiver(receiver);
        }
        if(dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }
}
